// 回车键的code h5是13 app是66
let enterCode = 13
// #ifdef APP
enterCode = 66
// #endif

/**
 * @description 将keyCode转为对应字符 
 * key h5keydown事件会返回code对应字符串 传e.key 不用处理，app传e.keyCode，通过此函数转为对应字符串
 */
const code2Num = (key) => {
  const codeMap = {
    '7': '0',
    '8': '1',
    '9': '2',
    '10': '3',
    '11': '4',
    '12': '5',
    '13': '6',
    '14': '7',
    '15': '8',
    '16': '9'
  }
  // #ifdef H5
  return key
  // #endif
  // #ifdef APP-PLUS
  return codeMap[key]
  // #endif
}

let code = ''
let lastTime, nextTime
let lastCode, nextCode

export const watchKeydown = (e, str='') => { 
  return new Promise(resolve => {
    const handlerCode = (e) => {
      nextCode = e.keyCode || e.which ||e.key
      if (!lastTime && !lastCode) {
        code += code2Num(e?.key || nextCode)
        console.log('扫码开始:' + code)
      }
      if (nextCode === enterCode) {
        if (code.length < 3) return // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
        const result = code
        code = ''
        lastCode = ''
        lastTime = ''
        console.log('扫码结束:' + result+',str,',str)
        resolve(result)
      }
      nextTime = new Date().getTime()
      if (lastCode && lastTime && nextTime - lastTime > 500) { // 当扫码前有keypress事件时,防止首字缺失
        // console.log('防止首字缺失。。。')
        code = code2Num(e?.key || nextCode)
      } else if (lastCode && lastTime) {
        // console.log('扫码中。。。')
        code += code2Num(e?.key || nextCode)
      }
      lastCode = nextCode
      lastTime = nextTime
    }
    handlerCode(e)
  })
}
